package ar.edu.unrn.lia.service.impl;

import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.NoResultException;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;

import ar.edu.unrn.lia.dao.UserDAO;
import ar.edu.unrn.lia.model.User;
import ar.edu.unrn.lia.service.UserService;

//@Service(value = "userService")
@Named("userService")
public class UserServiceImpl implements UserDetailsService, UserService {

	//@Autowired
	@Inject
	UserDAO entityDAO;

	public UserDAO getEntityDAO() {
		return entityDAO;
	}

	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		UserDetails userReturn = findByUsername(username);
		return userReturn;
	}

	private User findByUsername(String username) {
		User usuario = null;
		try {
			usuario = entityDAO.getEntityByUsername(username);

		} catch (NoResultException e) {

			if (usuario == null) {
				throw new UsernameNotFoundException("Usuario no existe.");
			}
		}

		return usuario;

	}

	@Transactional(readOnly = true)
	public Long getCount(Map<String, String> filters) {
		return getEntityDAO().count(
				getEntityDAO().getSearchPredicates(getEntityDAO().rootCount(),
						filters));
	}

	@Transactional(readOnly = true)
	public List<User> getList(Integer page, Integer pagesize,
			Map<String, String> filters, String sortField, Boolean asc) {
		return getEntityDAO().listwithPag(
				getEntityDAO().getSearchPredicates(getEntityDAO().rootCount(),
						filters), page, pagesize, sortField, asc);
	}

	@Transactional
	public void save(User entity) {
		getEntityDAO().create(entity);
	}

	@Transactional
	public void delete(User entity) {
		getEntityDAO().delete(entity);
	}

	@Transactional
	public void update(User entity) {
		getEntityDAO().update(entity);
	}

	public User getEntityById(Long id) {
		return getEntityDAO().read(id);
	}

	public List<User> getAll() {
		return getEntityDAO().findAll();
	}

}